import socket from '@ohos.net.socket';
import { BasicDecoder } from '../BasicDecoder';
import { Address, BasicNetworkUtil, Type } from '../BasicNetworkUtil';

export class TcpUtils extends BasicNetworkUtil {
  private socket = socket.constructTCPSocketInstance();

  constructor(decoder: BasicDecoder, type: Type, address: Address) {
    super(decoder, type, address);
  }

  public recvBinary(callback: (data: ArrayBuffer) => void): void {
    this.socket.on('message', (value) => {
      callback(value.message);
    });
  }

  public close() {
    this.socket.close().then((value) => {
      console.log('close success');
    }).catch((error) => {
      console.log('close error');
    });
  }

  public send(sendDataString: string | ArrayBuffer) {
    this.socket.send({ data: sendDataString }).then((value) => {
      console.log('send success');
    }).catch((error) => {
      console.log('send error');
    });
  }

  public recv(callback: (data: Map<string, number>) => void): void {
    this.socket.on('message', (value) => {
      let recvData = this.decoder.decode(value.message);
      callback(recvData);
    });
  }

  public init() {
    if (this.type == Type.local) { //本地作为服务器
      this.socket.bind({ address: this.address.ip, port: this.address.port }).then((value) => {
        console.log('listen success');
      }).catch((error) => {
        console.log('listen error');
      });
    } else if (this.type == Type.remote) { //本地作为客户端
      let ip = super.address.ip;
      this.socket.bind({ address: ip, family: 1 }).then(() => {
        console.log('bind success');
        this.socket.connect({
          address: { address: this.address.ip, port: this.address.port, family: 1 },
          timeout: 1000
        }).then((value) => {
          console.log('connect success');
        }).catch((error) => {
          console.log('connect error');
        });
      }).catch((error) => {
        console.log('bind error');
      });

    }
  }
}